//
//  NSString+ATKit.m
//  Postre
//
//  Created by CoderLT on 2017/6/24.
//  Copyright © 2017年 CoderLT. All rights reserved.
//

#import "NSString+ATKit.h"


@implementation NSDate (ATKit)
- (BOOL)isThisYear {
    return self.year == [NSDate date].year;
}
- (BOOL)isTomorrow {
    NSDate *added = [self dateByAddingDays:-1];
    return [added isToday];
}
- (NSString *)smartDisplay {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    // 如果是真机调试，转换这种欧美时间，需要设置locale
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    
    // 当前时间
    NSDate *now = [NSDate date];
    
    // 日历对象（方便比较两个日期之间的差距）
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // NSCalendarUnit枚举代表想获得哪些差值
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 计算两个日期之间的差值
    NSDateComponents *cmps = [calendar components:unit fromDate:self toDate:now options:0];
    
    if (self.timeIntervalSinceNow > 0) {
        if ([self isTomorrow]) { // 明天
            fmt.dateFormat = [NSString stringWithFormat:@"%@ HH:mm", @"明天"];
            return [fmt stringFromDate:self];
        } else if ([self isTomorrow]) { // 今天
            fmt.dateFormat = [NSString stringWithFormat:@"%@ HH:mm", @"今天"];
            return [fmt stringFromDate:self];
        } else if ([self isThisYear]) { // 今年的其他日子
            fmt.dateFormat = @"MM-dd HH:mm";
            return [fmt stringFromDate:self];
        }
        else {
            fmt.dateFormat = @"yyyy-MM-dd HH:mm";
            return [fmt stringFromDate:self];
        }
    }
    else if ([self isThisYear]) { // 今年
        if ([self isYesterday]) { // 昨天
            fmt.dateFormat = [NSString stringWithFormat:@"%@ HH:mm", @"昨天"];
            return [fmt stringFromDate:self];
        } else if ([self isToday]) { // 今天
            if (cmps.hour >= 1) {
                return [NSString stringWithFormat:@"%d%@", (int)cmps.hour, @"小时前"];
            } else if (cmps.minute >= 1) {
                return [NSString stringWithFormat:@"%d%@", (int)cmps.minute, @"分钟前"];
            } else {
                return @"刚刚";
            }
        } else { // 今年的其他日子
            fmt.dateFormat = @"MM-dd HH:mm";
            return [fmt stringFromDate:self];
        }
    } else { // 非今年
        fmt.dateFormat = @"yyyy-MM-dd HH:mm";
        return [fmt stringFromDate:self];
    }

    return nil;
}
@end


@implementation NSString (ATKit)
- (NSDate *)dateFromISOFormat {
    return [NSDate dateWithISOFormatString:self];
}
- (NSDate *)dateFromFormat:(NSString *)dateFormat {
    return [NSDate dateWithString:self format:dateFormat];
}

- (NSString *)EncTel {
    NSUInteger loc = [self rangeOfString:@"@"].location;
    if (loc != NSNotFound) {
        if (loc > 1) {
            NSUInteger count = MIN(loc - 1, 4);
            NSString *replaceStr = @"";
            for (int i = 0; i < count; i++) {
                replaceStr = [replaceStr stringByAppendingString:@"*"];
            }
            return [self stringByReplacingCharactersInRange:NSMakeRange(1, count) withString:replaceStr];
        }
        else {
            return self;
        }
    }
    else if (self.length >= 11) {
        return [self stringByReplacingCharactersInRange:NSMakeRange(self.length - 8, 4) withString:@"****"];
    }
    return self;
}
@end


@implementation NSString (URLParams)
/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
- (NSDictionary *)getURLParameters {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = self;
    NSRange range = [self rangeOfString:@"?"];
    if (range.location != NSNotFound) {
        parametersString = [parametersString substringFromIndex:range.location + 1];
    }
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            // 过滤title[0] / title[1] 这种情况
            key = [key stringByReplacingRegex:@"\\[[\\d ]*\\]" options:0 withString:@""];
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}
@end

@implementation UIColor (FDLive)
+ (instancetype)fd_ColorWithString:(NSString *)colorString {
    NSArray<NSString *> * array = [colorString componentsSeparatedByString:@"#"];
    if (array.count > 1 && [[array firstObject] length]) {
        CGFloat alpha = [array firstObject].floatValue / 100.0f;
        colorString = [NSString stringWithFormat:@"%@%02lx", array.lastObject, (unsigned long)(alpha * 255.0f + 0.5f)];
    }
    return [UIColor colorWithHexString:colorString];
}
@end
